%%%-------------------------------------------------------------------
%% @doc mqeg_consumers_sup top level supervisor.
%% @end
%%%-------------------------------------------------------------------
-module(mqeg_consumers_sup).
-behaviour(supervisor).

-export([start_link/0]).
-export([init/1]).
-export([get_consumer/1]).
-export([del_consumer/1]).

-define(SERVER, ?MODULE).

start_link() ->
    supervisor:start_link({local, ?SERVER}, ?MODULE, []).

%% sup_flags() = #{strategy => strategy(),         % optional
%%                 intensity => non_neg_integer(), % optional
%%                 period => pos_integer()}        % optional
%% child_spec() = #{id => child_id(),       % mandatory
%%                  start => mfargs(),      % mandatory
%%                  restart => restart(),   % optional
%%                  shutdown => shutdown(), % optional
%%                  type => worker(),       % optional
%%                  modules => modules()}   % optional
init([]) ->
    SupFlags = #{ strategy  => simple_one_for_one
                , intensity => 0
                , period    => 1
                },
    ChildSpec = #{ id       => mqeg_consumer
                 , start    => {mqeg_consumer, start_link, []}
                 , restart  => temporary
                 , shutdown => brutal_kill
                 , type     => worker
                 , modules  => [mqeg_consumer]
                 },
    {ok, {SupFlags, [ChildSpec]}}.


get_consumer(Name) ->
    case mqeg_misc:get_singleton({consumer, Name}) of
        undefined ->
            {ok, Pid} = supervisor:start_child(?SERVER, [Name]),
            mqeg_misc:set_singleton({consumer, Name}, Pid),
            Pid;
        Pid ->
            Pid
    end.

del_consumer(Name) ->
    mqeg_misc:set_singleton({consumer, Name}, undefined).

%% internal functions
